// 保存配置到Chrome存储
function saveSettings() {
  const enableFilter = document.getElementById('enableFilter').checked;
  const minImages = parseInt(document.getElementById('minImages').value) || 1;

  chrome.storage.sync.set({
    enableFilter,
    minImages,
  }, () => {
    // 通知content script配置已更新
    chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, {
          type: 'SETTINGS_UPDATED',
          settings: { enableFilter, minImages }
        });
      }
    });
  });
}

// 保存自动刷新设置
function saveAutoRefreshSetting() {
  const autoRefresh = document.getElementById('auto-refresh').checked;
  chrome.storage.sync.set({ autoRefresh });
  
  // 通知content script自动刷新设置变化
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    if (tabs[0]) {
      chrome.tabs.sendMessage(tabs[0].id, {
        type: 'AUTO_REFRESH_UPDATED',
        autoRefresh: autoRefresh
      });
    }
  });
}

// 从Chrome存储加载配置
function loadSettings() {
  chrome.storage.sync.get({
    enableFilter: true,
    minImages: 1,
    filteredCount: 0,
    autoRefresh: true
  }, (items) => {
    document.getElementById('enableFilter').checked = items.enableFilter;
    document.getElementById('minImages').value = items.minImages;
    document.getElementById('auto-refresh').checked = items.autoRefresh;
    document.getElementById('status').textContent = `已过滤 ${items.filteredCount} 条回答`;
  });
}

// 标签页切换功能
function initTabs() {
  const tabs = document.querySelectorAll('.tab');
  const tabContents = document.querySelectorAll('.tab-content');

  tabs.forEach(tab => {
    tab.addEventListener('click', () => {
      // 移除所有活动状态
      tabs.forEach(t => t.classList.remove('active'));
      tabContents.forEach(content => content.classList.remove('active'));

      // 激活当前标签
      tab.classList.add('active');
      const targetTab = tab.dataset.tab;
      document.getElementById(`${targetTab}-tab`).classList.add('active');

      // 如果切换到图片标签页，加载图片并通知content script
      if (targetTab === 'images') {
        loadImages();
        notifyContentScriptTabActive(true);
      } else {
        notifyContentScriptTabActive(false);
      }
    });
  });
}

// 加载图片数据
function loadImages() {
  const loadingEl = document.getElementById('images-loading');
  const gridEl = document.getElementById('images-grid');
  const noImagesEl = document.getElementById('no-images');
  const countEl = document.getElementById('images-count');

  // 显示加载状态
  loadingEl.style.display = 'block';
  gridEl.style.display = 'none';
  noImagesEl.style.display = 'none';

  // 请求content script收集图片
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    if (tabs[0]) {
      chrome.tabs.sendMessage(tabs[0].id, {
        type: 'COLLECT_IMAGES'
      }, (response) => {
        if (chrome.runtime.lastError) {
          console.log('通信错误，尝试监听返回消息...');
          // 设置超时等待
          setTimeout(() => {
            if (loadingEl.style.display !== 'none') {
              showNoImages('无法连接到页面，请确保在知乎页面使用');
              loadingEl.style.display = 'none';
            }
          }, 3000);
          return;
        }

        if (response && response.images && response.images.length > 0) {
          displayImages(response.images);
          countEl.textContent = `找到 ${response.images.length} 张图片`;
        } else {
          showNoImages();
          countEl.textContent = '未找到图片';
        }

        loadingEl.style.display = 'none';
      });
    } else {
      showNoImages('无法获取当前页面信息');
      loadingEl.style.display = 'none';
    }
  });
}

// 显示图片网格
function displayImages(images) {
  const gridEl = document.getElementById('images-grid');
  gridEl.innerHTML = '';
  gridEl.style.display = 'grid';

  images.forEach((image, index) => {
    const imageItem = document.createElement('div');
    imageItem.className = 'image-item';
    imageItem.innerHTML = `<img src="${image.src}" alt="${image.alt || ''}" loading="lazy">`;
    
    // 点击图片在新标签页打开
    imageItem.addEventListener('click', () => {
      chrome.tabs.create({ url: image.src });
    });

    gridEl.appendChild(imageItem);
  });
}

// 显示无图片状态
function showNoImages(message) {
  const gridEl = document.getElementById('images-grid');
  const noImagesEl = document.getElementById('no-images');
  
  gridEl.style.display = 'none';
  noImagesEl.style.display = 'block';
  
  if (message) {
    noImagesEl.querySelector('p').textContent = message;
  }
}

// 通知content script标签页状态
function notifyContentScriptTabActive(isActive) {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    if (tabs[0]) {
      chrome.tabs.sendMessage(tabs[0].id, {
        type: 'IMAGES_TAB_STATUS',
        isActive: isActive,
        autoRefresh: document.getElementById('auto-refresh').checked
      });
    }
  });
}

// 监听配置变化
document.getElementById('enableFilter').addEventListener('change', saveSettings);
document.getElementById('minImages').addEventListener('change', saveSettings);
document.getElementById('auto-refresh').addEventListener('change', saveAutoRefreshSetting);

// 刷新图片按钮
document.getElementById('refresh-images').addEventListener('click', loadImages);

// 弹窗关闭时通知content script
function notifyPopupClosed() {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    if (tabs[0]) {
      chrome.tabs.sendMessage(tabs[0].id, {
        type: 'IMAGES_TAB_STATUS',
        isActive: false,
        autoRefresh: false
      });
    }
  });
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
  loadSettings();
  initTabs();
});

// 弹窗卸载时清理
window.addEventListener('beforeunload', notifyPopupClosed);

// 监听来自content script的消息更新
chrome.runtime.onMessage.addListener((message) => {
  if (message.type === 'UPDATE_FILTERED_COUNT') {
    document.getElementById('status').textContent = `已过滤 ${message.count} 条回答`;
    chrome.storage.sync.set({ filteredCount: message.count });
  } else if (message.type === 'AUTO_REFRESH_IMAGES') {
    // 处理自动刷新的图片数据
    const currentTab = document.querySelector('.tab.active');
    const countEl = document.getElementById('images-count');
    
    if (currentTab && currentTab.dataset.tab === 'images') {
      if (message.images && message.images.length > 0) {
        displayImages(message.images);
        countEl.textContent = `找到 ${message.images.length} 张图片 (已自动刷新)`;
        console.log('[自动刷新] 图片列表已更新');
      }
    }
  } else if (message.images) {
    // 处理手动请求的图片数据返回
    const loadingEl = document.getElementById('images-loading');
    const countEl = document.getElementById('images-count');
    
    if (loadingEl && loadingEl.style.display !== 'none') {
      if (message.images.length > 0) {
        displayImages(message.images);
        countEl.textContent = `找到 ${message.images.length} 张图片`;
      } else {
        showNoImages();
        countEl.textContent = '未找到图片';
      }
      loadingEl.style.display = 'none';
    }
  }
});